import { Toast } from 'vant'
import Lockr from "../assets/js/Lockr";
import aes from "@/util/Aes.js";
import store from "../store";
import axios from "axios";
import App from "../App";
import config from "../config";
import Account from "./Account";
import qs from 'qs';
import initSensors from './sensors';
import wx from 'weixin-js-sdk';
import { shareDotNum } from '@/util/api.js';
export default {
  searchIphoneNum(str) { //全局手机号脱敏
    let reg = /1([3-9]{1}\d{1})\d{4}(\d{4})/g;
    return str = str.replace(reg, "1$1****$2");
  },
  msySkipSinePage(type, id, orgId = '0000') { //msyh 跳转通行证页面       type 区分直播间 回看  id 房间id和回看id    orgId  需要传的参数
    let hzbSelf;
    if (type == 'live') {
      hzbSelf = 'liveRoom'
    } else if (type == 'back') {
      hzbSelf = 'liveBack'
    }
    window.location.href = config.MSYH_WX.txzRegUrl + '&hzbSelf=' + hzbSelf + '&id=' + id + '&orgId=' + orgId +
      '&serviceCode=' + 'E002' + orgId + id
  },
  copyTxt(text, fn) { // 复制功能    text 需要复制的文本    fn  callback
    if (typeof document.execCommand !== 'function') {
      console.log('复制失败，请长按复制')
      return
    }
    var dom = document.createElement('textarea')
    dom.value = text
    dom.setAttribute('style', 'display: block;width: 1px;height: 1px;')
    document.body.appendChild(dom)
    dom.select()
    var result = document.execCommand('copy')
    document.body.removeChild(dom)
    if (result) {
      //console.log('复制成功')
      typeof fn === 'function' && fn()
      return
    }
    if (typeof document.createRange !== 'function') {
      console.log('复制失败，请长按复制')
      return
    }
    var range = document.createRange()
    var div = document.createElement('div')
    div.innerhtml = text
    div.setAttribute('style', 'height: 1px;fontSize: 1px;overflow: hidden;')
    document.body.appendChild(div)
    range.selectNode(div)
    var selection = window.getSelection()
    //console.log(selection)
    if (selection.rangeCount > 0) {
      selection.removeAllRanges()
    }
    selection.addRange(range)
    document.execCommand('copy')
    typeof fn === 'function' && fn()
    //console.log('复制成功')
  },
  getShareUrl(channel, urlPath) { //分享Url
    return config.SHARE_API + '?channel=' + channel + '&path=' + encodeURIComponent(urlPath);
  },
  //拼接当前页面的url
  getCurPageUrl(type, id,deleteUn) { //区分直播间 live 和回看 back home为首页地址       id 房间id和回看id
    if(deleteUn){
      if (type == 'live') {
        return window.location.protocol + "//" + window.location.host + "/#/" + channel + "/liveRoom/" + id +'?passEnRc=true'
      } else if (type == 'back') {
        return window.location.protocol + "//" + window.location.host + "/#/" + channel + "/liveBack/" + id +'?passEnRc=true'
      } else if (type == 'home') {
        return window.location.protocol + "//" + window.location.host + "/#/" + channel + "/home";
      }
    }else{
      if (type == 'live') {
        return window.location.protocol + "//" + window.location.host + "/#/" + channel + "/liveRoom/" + id + "?fromUn=" +
          store.state.userInfo.un;
      } else if (type == 'back') {
        return window.location.protocol + "//" + window.location.host + "/#/" + channel + "/liveBack/" + id + "?fromUn=" +
          store.state.userInfo.un;
      } else if (type == 'home') {
        return window.location.protocol + "//" + window.location.host + "/#/" + channel + "/home";
      }
    }   
  },
  computeIOSStatusbarHeight() {
    const screenWidth = window.screen.width
    const screenHeight = window.screen.height
    if ((screenWidth === 375 && screenHeight === 812) ||
      (screenWidth === 414 && screenHeight === 896)) {
      return 44
    } else if ((screenWidth === 390 && screenHeight === 844) ||
      (screenWidth === 428 && screenHeight === 926)) {

      return 48
    } else if ((screenWidth === 375 && screenHeight === 667) ||
      (screenWidth === 414 && screenHeight === 736) ||
      (screenWidth === 320 && screenHeight === 568)) {

      return 20
    } else {
      //iphone4
      return 20
    }
  },
  //打点 统计数据
  dotNum(sessionId, streamType = 12, actionValue =
    1) { //场次id     视频类型：1-预告 2-直播 3-回看 10-全局统计 11-商品点击 12-页面  行为：1-进入 2-离开 3-点击播放 4-留言 5-点赞 6-关注 7-分享 8-开播 9-关播 10-最高峰值
    var argumentData = {
      sessionId: sessionId, //场次id
      streamType: 12, //视频类型：1-预告 2-直播 3-回看 10-全局统计 11-商品点击 12-页面
      actionValue: 1, //行为：1-进入 2-离开 3-点击播放 4-留言 5-点赞 6-关注 7-分享 8-开播 9-关播 10-最高峰值
      playSource: this.getPlatform(), //微信 app
      url: window.location.href, //当前的url
    };
    axios.post("/h5live/recordData", argumentData, {
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(
        res => {
          //console.log(res)
        },
        err => {
          console.log(err);
        }
      );
  },
  disposeTx(txImg) {
    if (window.channel == 'gdkj') {
      return txImg
    } else {
      return txImg.replace('http://', '//')
    }
  },
  // 神策打点来源
  sensorsSource() {
    if (window.terminal.isZxjtApp) {
      return "app";
    } else {
      let plat = "web"
      var ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        plat = 'wx';
      }
      return plat;
    }
  },
  getPlatform() {
    let plat = "web"
    var ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      plat = 'wx';
    } else if (window.terminal.android || window.terminal.ios) {
      plat = 'app';
    }
    return plat;
  },
  getEnterSource() {
    if (window.terminal.isZxjtApp) {
      return "app";
    } else {
      let plat = "web"
      var ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == 'micromessenger') {
        plat = 'wx';
      } else {
        plat = 'other';
      }
      return plat;
    }
  },
  //截取字符串后面的字符串 保留前面的
  cutStrFun(strName, str) {
    let index = str.lastIndexOf(strName)
    str = str.substring(0, index);
    return str
  },
  //获取url的参数 paraName 获取后面的参数  url  不传默认是
  GetUrlParam(paraName, url = document.location.href.toString()) {
    //var url = document.location.toString();　　　　
    var arrObj = url.split("?");
    if (arrObj.length > 1) {
      var arrPara = arrObj[1].split("&");
      var arr;
      for (var i = 0; i < arrPara.length; i++) {
        arr = arrPara[i].split("=");
        if (arr != null && arr[0] == paraName) {
          return arr[1];
        }
      }
      return null;
    } else {
      return null;
    }
  },
  /**
   * 获取当前 url 参数字符串
   * @param {String} 要获取的参数名称
   * @returns {String} 要获取的参数
   */
  GetNewUrlParam(name) {
    let params = new URL(window.location.href).searchParams;
    return params.get(name)
  },
  //url转base_self4
  getBase64(url, source, callback) {
    //通过构造函数来创建的 img 实例，在赋予 src 值后就会立刻下载图片，相比 createElement() 创建 <img> 省去了 append()，也就避免了文档冗余和污染
    var Img = new Image(),
      dataURL = "";
    Img.setAttribute("crossOrigin", "Anonymous"); // 解决控制台跨域报错的问题

    Img.onerror = err => {
      if (source == 'tx') { //头像
        let mrUrl = require('../assets/images/gd_mr.png');
        callback ? callback(mrUrl) : null; //调用回调函数
        console.log("err", err);
      } else if (source == 'back') { //封面图
        let mrImgPoster = require('../assets/images/saasMoRen.jpg');
        callback ? callback(mrImgPoster) : null; //调用回调函数
        console.log("err", err);
      }
    };
    Img.onload = function () {
      //要先确保图片完整获取到，这是个异步事件
      var canvas = document.createElement("canvas"), //创建canvas元素
        width = Img.width, //确保canvas的尺寸和图片一样
        height = Img.height;
      canvas.width = width;
      canvas.height = height;
      canvas.getContext("2d").drawImage(Img, 0, 0, width, height); //将图片绘制到canvas中
      dataURL = canvas.toDataURL("image/png"); //转换图片为dataURL
      callback ? callback(dataURL) : null; //调用回调函数
    };
    Img.src = url + "?v=" + Math.random(); // 处理缓存,fix缓存bug,有缓存，浏览器会报错;

    if (Img.complete) Img.onload();
  },
  toastMessage(txt, t = 3000) {
    Toast({
      message: txt,
      duration: t,
      type: "txt",
      className: ['my-toast', 'my-toast-ps']
    })
  },
  toastSuccess(txt, t = 3000) {
    Toast({
      message: txt,
      duration: t,
      type: "success",
      className: ['my-toast', 'my-toast-ps']
    })
  },
  // 拉起 app 手机登录
  ykDisposeFun () {
    if (window.terminal.isZxjtApp) {
      if (window.terminal.isZxjtAndroid) {
        console.log("run zxjt android login phone")
        KDS_Native.getUserInfo('baseInfo')
      } else if (window.terminal.isZxjtIos) {
        console.log("run zxjt ios login phone")
        window.webkit.messageHandlers.getUserInfo.postMessage({ "tradeAccountInfo": { "baseInfo": "1" }, "baseInfo": "1" })
        // window.webkit.messageHandlers.getUserInfo.postMessage(JSON.stringify({"tradeAccountInfo":{"baseInfo":"1"}}))
      }
    } else if (window.terminal.isZxjtqhApp) {
      this.gotoLogin();//调登录
    } else {
      this.toastMessage('当前为游客模式')
    }
  },
  // 拉起 app 资金账号登录
  ykDisposeZjzhFun() {
    if (window.terminal.isZxjtApp) {
      if (window.terminal.isZxjtAndroid) {
        console.log("run zxjt android login zjzh")
        KDS_Native.getUserInfo('ptjy')
      } else if (window.terminal.isZxjtIos) {
        console.log("run zxjt ios login zjzh")
        window.webkit.messageHandlers.getUserInfo.postMessage({ "tradeAccountInfo": { "ptjy": "1" }, "ptjy": "1" })
      }
    } else {
      this.toastMessage('当前为游客模式')
    }
  },
  deleteT(source, location, len) {
    return source.substring(0, location) + source.substring(location + len, source.length);
  },
  filterUrl(name, vue = true) { // vue = true 去除中间带#处的参数，否则去除结尾的参数
    var loca = window.location;
    var baseUrl = loca.origin + loca.pathname;
    let query;
    let ref = '';
    let pos = 0;
    if (vue) {
      query = loca.search.substr(1);
      ref = location.href.substr(location.href.lastIndexOf('#/'))
    } else {
      let script = location.href.substr(location.href.indexOf('#/') + 1)
      pos = script.lastIndexOf('?');
      ref = location.href.substr(0, location.href.lastIndexOf('#/')) + '#'
      if (pos != -1) {
        query = script.substr(pos + 1);
        ref += script.substr(0, pos)
      } else {
        query = ''
        ref += script
      }
    }

    let url = query == '' ? '' : '?' + query;
    if (query.indexOf(name) > -1) {
      var obj = {}
      var arr = query.split("&");
      for (var i = 0; i < arr.length; i++) {
        arr[i] = arr[i].split("=");
        obj[arr[i][0]] = arr[i][1];
      };
      delete obj[name];
      let path = JSON.stringify(obj).replace(/[\"\{\}]/g, "").replace(/\:/g, "=").replace(/\,/g, "&");
      url = (path == '' ? '' : '?' + path);
    }

    if (vue) {
      return baseUrl + url + ref;
    } else {
      return ref + url;
    }
  },
  async buildYk(channel, reload = false) {
    let ykToken = Lockr.getLocal("ykToken");
    if (ykToken && !reload) {
      return new Promise((resolve, reject) => {
        resolve(ykToken)
      })
    } else {
      let res = await axios.get("/auth/buildYk?channel=" + channel + '&source=' + this.getEnterSource())
      return new Promise((resolve, reject) => {
        if (res.data.code == "000000") {
          if (res.data.token != undefined) {
            store.dispatch("setYk", true);
            Lockr.setLocal("ykToken", res.data.token)
            resolve(res.data.token)
          } else {
            reject("err")
          }
        } else {
          reject("err")
        }
      })
    }
  },
  async buildChannelAc(params) {
    let r = {
      "err": 0,
      "token": "",
      "source": "",
      "isYk": false
    }
    let sign = params.get('sign')
    let apiUrl = 'buildChannelAc';
    if (sign) {
      apiUrl = 'buildZgyhApp';
    }
    let res = await axios.post("/auth/" + apiUrl, params);
    // alert(params)
    if (res.data.code == "000000") {
      if (res.data.data != undefined) {
        r.token = res.data.data.token
        r.source = res.data.data.source
        r.isYk = res.data.data.isYk
      } else {
        r.err = 1
      }
    } else {
      let ykRes = await axios.get("/auth/buildYk?channel=" + channel + '&source=app')
      if (ykRes.data.code == "000000") {
        if (ykRes.data.token != undefined) {
          r.token = res.data.token
          r.source = "app"
          r.isYk = true
        } else {
          r.err = 1
        }
      } else {
        r.err = 1
      }
    }
    return new Promise((resolve, reject) => {
      if (r.err == 0) {
        resolve(r)
      } else {
        reject("err")
      }
    })
  },
  getQueryString(name, isVue = true) {
    try {
      let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      let r = null
      if (isVue) {
        r = window.location.search.substr(1).match(reg);
      } else {
        let path = location.href.substr(location.href.indexOf('#/'))
        r = path.substr(path.lastIndexOf('?')).substr(1).match(reg);
      }
      if (r != null) return r[2];
    } catch (e) {
      console.log("getQueryString catch err", e)
    }
    return null;
  },
  loadBridge(url, callback = null, more = '') {
    var script = document.createElement('script')
    // onload fires even when script fails loads with an error.
    if (callback) {
      script.onload = callback
    }
    // onerror fires for malformed URLs.
    script.onerror = onerror
    script.src = url
    if (more === 'gyzq') {
      script['td-appid'] = "APPID"
    }
    document.head.appendChild(script)
  },
  initVue(tokenRes, channel, source) {
    Account.setCacheToken(tokenRes)
    if (channel == config.ZXYHXYK && window.terminal.weixin && this.getQueryString("code", false)) {
      location.replace(this.filterUrl("code", false))
    }

    Vue.prototype.$token = tokenRes;
    Vue.prototype.$source = source

    axios.interceptors.request.use(
      cfg => {
        cfg.headers["token"] = Vue.prototype.$token
        cfg.headers["channel"] = channel
        cfg.headers['source'] = Vue.prototype.$source
        cfg.headers['plat'] = store.state.sourcePlat
        return cfg;
      },
      function (error) {
        return Promise.reject(error);
      }
    );

    axios.interceptors.response.use(
      function (response) {
        if (response.data && response.data.code) {
          if (response.data.code == "100001") {

          }
        }
        return response;
      },
      function (error) {
        return Promise.reject(error);
      }
    );

    //console.log(tokenRes,channel,source)
    if (!window.needReload && !isInitVue) {
      this.initSimpleVue()
    }

  },
  initSimpleVue() {
    let router = Vue.prototype.$myrouter
    isInitVue = true
    new Vue({
      el: "#app",
      router,
      components: {
        App
      }, // 1.0的写法
      template: "<App/>"
      // render:h=>h(App)   //2.0写法
    })
  },
  getZGYHLoginInfo() { //中行用户信息
    //console.log('调用函数')
    window.c_plugins.merchantBridge.getBocCustomerInfoForBocLive(res => {
      //console.log('调用登录信息接口', res)
      let params = new URLSearchParams();
      params.append('openid', res.openid);
      params.append('nickname', res.nickname);
      params.append('headimgurl', res.headimgurl);
      params.append('sign', res.sign);
      this.buildChannelAc(params).then(r => {
        if (window.needReload) {
          Account.setCacheToken(r.token)
          window.location.reload()
        } else {
          let source = r.source
          Lockr.set('source', source)
          store.dispatch("setYk", r.isYk);
          this.initVue(r.token, 'zgyh', 'app')
        }
      }, err => {
        this.errMsg("获取接入账号信息异常，请稍后重试！")
      })
    }, err => {
      console.log(err)
    })
  },
  loginPage() { //App登录页面
    window.needReload = true
    window.c_plugins.merchantBridge.continueAfterLogin(res => {
      this.getZGYHLoginInfo()
    }, err => { }, {
      loginLevel: '1'
    })
  },
  errMsg(msg) {
    this.toastMessage(msg)
    throw new Error('channel filter');
  },
  errCodeCallback(err) {
    try {
      if (err.response.status == '504' || err.response.status == '500' || err.response.status == '502') {
        this.gotoBusyPage()
      }
    } catch (e) { }
  },
  gotoBusyPage() {
    if (!isInitVue) {
      this.initSimpleVue()
    }
    Vue.prototype.$myrouter.push('/' + channel + '/noEnterPage')
  },
  gszqGoLogin(url = '') { // url 默认空会回调当前页面
    let data = JSON.stringify({
      funcname: '22435',
      args: {
        url
      }
    })

    if (window.terminal.android) {
      //android
      window.MyWebView.callNativeFunction(data)
    } else {
      //ios
      window.webkit.messageHandlers.callNativeFunction.postMessage(data)
    }
  },
  // 时间差（直播时长）
  getDateDiff(startTime, endTime) {
    let d1 = startTime.replace(/\-/g, "/");
    let date1 = new Date(d1);
    let d2 = endTime.replace(/\-/g, "/");
    let date2 = new Date(d2);
    // 时间相差秒数
    let dateDiff = (date2.getTime() - date1.getTime()) / 1000;
    let seconds = parseInt(dateDiff); // 秒
    let minutes = 0; // 分
    let hours = 0; // 小时
    if (seconds > 60) {
      minutes = parseInt(seconds / 60);
      seconds = parseInt(seconds % 60);
      if (minutes > 60) {
        hours = parseInt(minutes / 60);
        minutes = parseInt(minutes % 60);
      }
    }
    let result = "" + parseInt(seconds);
    if (result < 10) {
      result = '0' + result;
    }
    if (minutes > 0) {
      result = "" + parseInt(minutes) + ":" + result;
      if (minutes < 10) {
        result = '0' + result;
      }
    } else {
      result = '00:' + result;
    }
    if (hours > 0) {
      result = "" + parseInt(hours) + ":" + result;
      if (hours < 10) {
        result = '0' + result;
      }
    } else {
      result = '00:' + result;
    }
    return result;

  },

  // 中信信用卡 邀 分享
  shareOut(roomInfo, roomType, roomId, un, defaultInfo) {
    let url = roomType + '/' + roomId + '?fromUn=' + un;
    let shareUrl = this.getShareUrl(window.channel, url)
    if (window.zx) {
      zx.share({
        name: 'weixin', //分享渠道名
        title: roomInfo.shareTitel || roomInfo.shareTitle || '【' + defaultInfo.name + '】一起来看直播吧！', //分享标题
        content: roomInfo.shareSubtitle || '精彩直播，尽在' + defaultInfo.name + '手机直播！', //分享副标题
        thumbImage: roomInfo.shareImgurl || defaultInfo.icon || '', //分享图标链接
        shareUrl, //分享链接
        success: function (res) {
          console.log(res)
        },
        fail: function (res) {
          console.log(res)
        },
        complete: function (res) {
          console.log(res)
        }
      }).then(function () {
        console.log('分享成功')
        return true
      }).catch(function (error) {
        console.log('分享失败', error)
      })
    }
  },

  zxxykKeepLogin() {
    let _this = this
    console.log("send keep login")
    zx.retainLoginState({
      success: function (res) {
        console.log("send keep login succ")
      },
      fail: function (res) {
        console.log("send keep login fail")
      },
      complete: function (res) { }
    })
  },
  //中银证券 签约提示框
  getRoomSignUp(roomId, vid) {
    axios.get('/zb/live/zy/roomSignUp?roomId=' + roomId + "&type=1" + "&vid=" + vid).then( // type 1直播  2视频
      res => {
        switch (res.data.code) {
          case '000000': //公开无限制观看直播
            this.checkMobileTip()
            break;
          // case '400001'://没有开通资金类账号
          //   store.dispatch("accountTipShow", true)
          //   store.dispatch("setTipCom", 'Reminder')
          //   break;
          case '400002': //没有投顾签约
            store.dispatch("consultant", true)
            store.dispatch("setTipCom", 'Reminder')
            break;
          case '400003': //没有签 投顾协议
            store.dispatch("consulAgree", true)
            store.dispatch("setTipCom", 'agreement')
            break;
          //					case '400005': //管理后台没有设置签署协议
          //						router.go(-1)
          //						break;
          case '400006': //用户扩展信息没有找到
            router.go(-1)
            break;
          case '400007': //没有签署白名单
            store.dispatch("whiteList", true)
            store.dispatch("setTipCom", 'Reminder')
            break;
          case '400009': //0<rl<10   风险评估过期
            store.dispatch("riskOver", true)
            store.dispatch("setTipCom", 'Reminder')
            break;
          case '400010': //10<=rl<14  风险评估等级不够
            store.dispatch("riskLow", true)
            store.dispatch("setTipCom", "Reminder")
            break;
          default:
            break;
        }
      },
      err => {
        console.log(err)
      }
    )
  },
  // 中银证券 私加号码提示框
  checkMobileTip() {
    axios.get("/zb/live/zy/checkMobileTip").then(
      res => {
        if (res.data.code == '000000') {
          if (res.data.data) { //不提示
            store.dispatch("setMobileTipFalse")
          } else {
            store.dispatch("setTipCom", "Reminder")
            store.dispatch("setMobileTipTrue")
          }
        } else {
          console.log(res.data.msg)
        }
      },
      err => {
        console.log(err);
      }
    )
  },

  //中银证券 是否展示顶部导航
  showTopNav(isShow, path) {
    if (!isShow && window.MyWebView) {
      let params = {
        action: '10061',
        url: path
      }
      window.MyWebView.tzt_hsCallNativeFunctionFromWeb("reqaction", JSON.stringify(params))
      return
    }
  },
  // 手机号脱敏
  telAddstar(text) {
    let textTrim = text.replace(/(^\s*)|(\s*$)/g, "");
    if (textTrim.length == '11' && (/^1[3456789]\d{9}$/.test(textTrim))) {
      return textTrim.substring(0, 3) + "****" + textTrim.substring(7, 11);
    } else {
      return text
    }
  },
  //中信银行调起登录
  zxyhLogin(currentUrl) {
    let url = ''
    if (currentUrl == 'mine') {
      url = currentUrl
    } else {
      let index = currentUrl.indexOf('/zxyh/');
      url = currentUrl.substring(index + 6)
    }
    console.log(url, 'currentUrl')
    if (window.terminal.isZxyhApp) { //window.bridgeReady
      console.log("window.bridgeReady:" + window.bridgeReady + "window.bank:" + window.bank +
        "window.bank.browserPlugin:" + window.bank.browserPlugin)
      if (window.bridgeReady && window.bank && window.bank.browserPlugin) {
        window.bank.browserPlugin.openByMenuId({
          menuId: '1008007',
          closePage: true,
          menuParams: {
            needLogin: '1',
            url, // 当前直播间场次url 可传''传空跳转至直播间列表页
          }
        })
      }
    }
  },
  // ios下键盘弹出点击空白不收起问题 sDom为input textarea
  objBlurFun(sDom, time = 100) {
    const isIphone = navigator.userAgent.toUpperCase().includes('IPHONE') // 判断ios环境
    if (isIphone) { // 如果是ios环境下
      let obj = document.querySelector(sDom)
      if (obj) {
        obj.addEventListener(
          'focus',
          () => {
            document.addEventListener('touchend', e => {
              this.docTouchend(time, obj, e)
            })
          },
          false
        )
      }
    }
  },
  // 元素失去焦点隐藏ihpone的软键盘
  docTouchend(time, obj, e) {
    if (e.target != obj) { // 点击 屏幕空白处的情况下
      setTimeout(() => {
        obj.blur()
        //window.scrollTo(0, 0);
        document.removeEventListener('touchend', this.docTouchend, false) // 收起之后 移除监听器
      }, time)
    } else { }
  },
  // 解决Ios键盘被遮挡
  onFocus(timerId) {
    let cnt = 0;
    setInterval(() => {
      if (cnt < 3) {
        cnt++;
      } else {
        clearInterval(timerId);
        this.timerId = null;
        return;
      }
      document.body.scrollTop = document.body.scrollHeight;
    }, 300);
  },
  onBlur(timerId) {
    if (this.timerId) {
      clearInterval(timerId);
      timerId = null;
    }
  },
  // 中信银行邀(分享)
  zxyhShareOut(roomInfo, roomType, roomId, un, defaultInfo) {
    let zbOrBack;
    if (roomType == 'liveRoom') {
      zbOrBack = '0'
    } else {
      zbOrBack = '1'
    }
    axios.get('/h5live/zx/shareLink?roomId=' + roomId + '&zbOrBack=' + zbOrBack).then(
      res => {
        if (window.bridgeReady && window.bank && window.bank.sharePlugin) {
          window.bank.sharePlugin.share({
              platforms: ['Wechat', 'WechatMoments'], //平台，微信好友、微信朋友圈
              shareType: 'webpage', //类型
              title: roomInfo.shareTitel || roomInfo.shareTitle || '【' + defaultInfo.name + '】一起来看直播吧！', //分享标题
              description: roomInfo.shareSubtitle || '精彩直播，尽在' + defaultInfo.name + '手机直播！', //分享描述
              webpageUrl: res.data.data, //分享链接
              thumbUrl: roomInfo.shareImgurl || defaultInfo.icon || '' //缩略图URL（可选）
            },
            function(result) { //成功回调
              console.log(result, 'result')
            },
            function (error) { //失败回调
              console.log(error, 'error')
            })
        }
      },
      err => {
        console.log(err)
      }
    )
  },
  // 是否是JSON
  isJSON(str) {
    if (typeof str == 'string') {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == 'object' && obj) {
          return true;
        } else {
          return false;
        }

      } catch (e) {
        return false;
      }
    }
  },

  // 设置留言和点赞里面的时间
  getTime() {
    let date = new Date();
    let seperator1 = "-";
    let seperator2 = ":";
    let month = date.getMonth() + 1; // 月份
    let strDate = date.getDate(); // 天
    let strHours = date.getHours(); // 小时
    let strMinutes = date.getMinutes(); // 分钟
    let strSec = date.getSeconds(); //秒
    let year = date.getFullYear(); //年
    // 单数前加 0
    month = /^\d$/.test(month) ? '0' + month : month;
    strDate = /^\d$/.test(strDate) ? '0' + strDate : strDate;
    strHours = /^\d$/.test(strHours) ? '0' + strHours : strHours;
    strMinutes = /^\d$/.test(strMinutes) ? '0' + strMinutes : strMinutes;
    strSec = /^\d$/.test(strSec) ? '0' + strSec : strSec;
    return (
      year +
      seperator1 +
      month +
      seperator1 +
      strDate +
      " " +
      strHours +
      seperator2 +
      strMinutes +
      seperator2 +
      strSec
    );
  },
  buildMsyhWxURL(hzbUrl) {
    //hzbUrl = hzbUrl.replace(/(.*)[\?&]{1}isUc=[01]+(.*)/,"$1$2")
    let url = config.MSYH_WX.host + "gw/pwx_wx/PerWXUserLogin.do"; // （数据接受地址，可修改）
    let wxNo = config.MSYH_WX.wxNo; // （总行gh号，可修改）
    let appid = config.MSYH_WX.appid; // （总行appid，可修改）
    let pageSign = config.MSYH_WX.pageSign; // （授权解密标识符，可修改）
    // echo -n // 'pwx_wxuser_login_authkey'|md5sum // 版本   uat pwx_wxuser_login_manager
    let redirect_uri = config.MSYH_WX.wxHost + "mcpWxAuth/wxAuth/pageCode"; // （跳转地址uat和版本区分，可修改）
    let commonStr = "&response_type=code&scope=snsapi_userinfo#wechat_redirect"; // （本行直接复制）
    //let hzbUrl = "http://10.15.45.126:8080/#/msyh/liveRoom/1409";
    hzbUrl = this.msyhUrlencode(this.msyhUrlencode(hzbUrl));
    //hzbUrl = this.msyhUrlencode(hzbUrl);
    //let pageParam = '{"param":{"pageParam":"'+hzbUrl+'"},"auth":"0","menuId":"WX100007"}';
    let pageParam = "{'param':{'pageParam':'" + hzbUrl + "'},'auth':'0','menuId':'WX100007'}";
    //let pageParam = JSON.stringify({'param':{'pageParam':hzbUrl},'auth':'0','menuId':'WX100007'});
    //console.log("pageParam is",pageParam)
    pageParam = this.msyhUrlencode(pageParam); // 若为ipad需要此行代码
    let encode = this.msyhUrlencode(redirect_uri + "?pageSign=" + pageSign + "&wxNo=" + wxNo + "&pageParam=" +
      pageParam);
    let str = "=" + appid + "&redirect_uri=" + encode + commonStr;
    str = this.msyhUrlencode(str);
    return url + "?wxNo=" + wxNo + "&authUrl=appid" + str + "&pageParam=" + this.msyhUrlencode(pageParam)

    // return res
    /*  console.log("res","11",typeof res.length)
      return res.replace(/'/g,"%27");*/
  },
  msyhUrlencode(str) {
    return encodeURIComponent(str).replace(/%20/gi, '').replace(/(!)|(')|(\()|(\))|(\~)/gi, item => {
      return '%' + item.charCodeAt(0).toString(16).toLocaleUpperCase();
    })
  },
  //抽奖计算角度
  computedDeg(gridNum = '8', index,) { //  参数1:gridNum数量  8    参数2:45deg 6 60deg index  商品的下标
    if (gridNum == '8') { //8格
      let num = 22.5 + 45 * (8 - index);
      return num;
    } else if (gridNum == '6') { //6格
      let num = 30 + 60 * (6 - index);
      return num;
    }

  },
  //zxyh 跳转外链
  openUrl(url) {
    if (window.bridgeReady && window.bank && window.bank.browserPlugin) {
      window.bank.browserPlugin.openCordovaExternalWebview({
        //链接地址
        url,
        //取消过度动画：
        forbidAnimation: "1",
        //是否关闭当前页面：
        closePage: false,
      },
        function (result) {
          //成功回调
        },
        function (error) {
          //失败回调
        }
      );
    }
  },
  //zxyh 新版跳转外链
  openUrlZxyh(url) {
    if (window.bridgeReady && window.bank && window.bank.browserPlugin) {
      window.bank.browserPlugin.openCordovaExternalWebview({
        url,
        //是否关闭当前webview
        closePage: false,
        //取消过度动画：
        forbidAnimation: "1",
        hideNavbar: true,
      },
        function (res) {
          console.log('结果', res)
        })
    }
  },
  zxyhDomOnload() {
    document.addEventListener('deviceready', function () {
      window.bridgeReady = true;
      console.log('桥接接口初始化完成')
      window.bank.appPlugin.getAppInfo(r => {
        if (window.terminal.iPhone) {
          window.versionNum = window.versionCompare(r.versionName, '7.5.3');//当前版本号  要求最低版本号
        } else if (window.terminal.android) {
          window.versionNum = window.versionCompare(r.versionName, '8.0.1');//当前版本号  要求最低版本号
        }
      })
    }, false)
  },
  //国盛证券 关闭 （我知道了）
  gszqGoBack() {
    let data = JSON.stringify({
      funcname: '22347',
    })
    if (window.terminal.android) {
      //android
      window.MyWebView.callNativeFunction(data)
    } else {
      //ios
      window.webkit.messageHandlers.callNativeFunction.postMessage(data)
    }
  },
  //处理数组
  clearUpArray(array, num) { //array 原数组   num  几个数组放一起
    let resultArray = [];
    for (let i = 0; i < array.length; i += num) {
      resultArray.push(array.slice(i, i + num));
    }
    return resultArray;
  },
  getActivityData(elementType, id, callBack) { //请求活动数据 elementType应用元素 0 首页 1直播间 2回看 3短视频  elementiId  id         targetType    0 app 1 微信
    let targetType = window.terminal.weixin ? '1' : '0';
    axios.get("/h5live/hzb/activity/icon?elementType=" + elementType + "&elementId=" + id + "&targetType=" + targetType)
      .then(res => {
        if (res.data.code == "000000") {
          callBack(res)
        } else { }
      })
      .catch(response => {
        console.log(response);
      });
  },
  //活动打点
  activityDotNumFun(type, iconId, activityId, elementType,
    elementId) { //type 0 入口, 1 入口活动   iconId 图标id   activityId 活动id   elementType,elementId 接口里面返回的参数
    //入口：PG_IC#${pageIconId}_TG#${targetType}
    //活动：PG_IC#${pageIconId}_TG#${targetType}_ACT#${activityId}_${elementType}#${elementId}
    let targetType = window.terminal.weixin ? '1' : '0';
    let seId;
    if (type == '0') { //入口图标
      seId = `PG_IC#${iconId}_TG#${targetType}`
    } else if (type == '1') { //点击跳转活动
      seId = `PG_IC#${iconId}_TG#${targetType}_ACT#${activityId}_${elementType}#${elementId}`
    }
    let argumentData = {
      sessionId: seId, //场次id
      streamType: 12, //视频类型：1-预告 2-直播 3-回看 10-全局统计 11-商品点击 12-页面
      actionValue: 1, //行为：1-进入 2-离开 3-点击播放 4-留言 5-点赞 6-关注 7-分享 8-开播 9-关播 10-最高峰值
      playSource: this.getPlatform(), //微信 app
      url: window.location.href, //当前的url
    };
    axios.post("/h5live/rcdData?type=" + type, argumentData, {
      headers: {
        "Content-Type": "application/json"
      }
    })
      .then(
        res => {
          //console.log(res)
        },
        err => {
          console.log(err);
        }
      );
  },
  //分享链接地址栏参数
  handleUrl(url, name) { //处理成对象 name
    let arr = url && url.split('?');
    let str = arr[1];
    let list = str.split('&');
    let newObj = list.reduce((pre, cur, index) => {
      let newArr = cur.split('=');
      pre[newArr[0]] = newArr[1];
      return pre;
    }, {})
    return {
      ...newObj
    }[name];
  },
  gszqShare(roomInfo, roomType, roomId, un, defaultInfo, roomRl) { //国盛证券分享
    let urlS = roomType + '/' + roomId + '?fromUn=' + un + '&roomRl=' + roomRl;
    let shareUrl = this.getShareUrl(window.channel, urlS);
    let data = JSON.stringify({
      "funcname": "22400",
      "args": {
        "title": roomInfo.shareTitel || roomInfo.shareTitle || '【' + defaultInfo.name + '】一起来看直播吧！', //分享标题,
        "message": roomInfo.shareSubtitle || '精彩直播，尽在' + defaultInfo.name + '手机直播！',
        "url": shareUrl,
        "sharetype": "99", //分享渠道（不指定渠道传99），0:微信  1:微信朋友圈 2:QQ好友 3:QQ空间 4:腾讯微博 99:客户端选择
      }
    })
    if (window.terminal.android) { //android
      window.MyWebView.callNativeFunction(data)
    } else { //ios
      window.webkit.messageHandlers.callNativeFunction.postMessage(data)
    }
  },
  componentCreated(obj) { //组件创建之前逻辑
    switch (channel) {
      case 'zhxyk': //中行信用卡
        if (obj.hasOwnProperty('isFirstPage')) {
          window.parent.postMessage({
            cmd: "pageGoBack",
            params: {
              isFirstPage: obj.isFirstPage,
              topTitleName: "上冰雪 找中行",
            }
          }, '*')
        }
        break;
      default:
        break;
    }
  },
  //封装axios
  requestAxios(type, url, cb) {
    axios[type](url)
      .then(res => {
        cb(res)
      })
      .catch(response => {
        console.log(response);
      });
  },
  async appUserJoin(authParam, channel, source) {
    return new Promise((resolve, reject) => {
      if (!authParam || authParam == 'N') {
        return reject('yk')
      }

      let params = new URLSearchParams();
      if (source) {
        params.append('source', source);
      } else {
        source = 'app'
      }
      params.append('channel', channel);
      params.append('authParam', authParam);

      this.buildChannelAc(params).then(r => {
        Lockr.set('source', r.source)
        //store.dispatch("setYk", r.isYk);
        this.initVue(r.token, channel, source)
        if (store.state.isYk && !r.isYk) {
          this.initUserInfo()
        }
        resolve('succ')
      }, err => {
        //this.gotoBusyPage()
        resolve('yk')
      })
    })

  },
  initUserInfo() {
    axios.get("/h5live/getUserInfo").then(
      res => {
        if (res.data.code == "000000") {
          let { un, openid } = res.data.data;
          initSensors(this.sensorsSource(), openid); // 神策初始化（获取用户信息之后）
          if (res.data.data.yk) {
            store.dispatch("setYk", true);
          } else {
            store.dispatch("setYk", false);
          }
          //console.log(res.data.data.wxpic)
          let TXUrl = res.data.data.wxpic;
          store.dispatch("setUserInfo", res.data.data);
          window.localStorage.setItem("userNickName", res.data.data.nickname);
          window.sessionStorage.setItem("TXUrl", TXUrl);
        } else if (res.data.code == "100001" && res.data.msg == '登录超时') {
          if (window.terminal.gdEx) {
            Account.gotoGdexAuth2()
          } else {
            this.buildYk(channel, true).then(resToken => {
              Account.setCacheToken(resToken)
              location.reload()
            }, err => {
              this.toastMessage('用户信息获取失败！')
            })
          }
        }
      },
      err => {
        //console.log("get userinfo ", err.response.status);
        this.errCodeCallback(err)
      }
    )
  },
  refreshUserInfo() {
    return new Promise((resolve, reject) => {
      axios.get("/h5live/getUserInfo").then((res)=>{
        if (res.data.code == "000000") {
          store.dispatch("setUserInfo", res.data.data);
          resolve();
        } else {
          reject();
        }
      }).catch(reject)
    })
  },
  zhxykSendLogin() {
    let param = {
      merChantNo: "",
      merH5Id: config.ZHXYK_MERH5ID,
      merChannelId: "",
      merChannelFlag: "greatWisdomLive",
    };

    window.parent.postMessage({
      cmd: "checkLoginInfo",
      params: param
    }, '*')
  },
  floatSendData( item = {} , openNewPage = '1') {  
    // 1.direction 0 横屏  1 竖屏   linkType 1  url  2  json
    const direction = store.state.floatVideoDirection;
    const { linkType , link } = item;
    let params;
    if( linkType === 1 ){
      params = {
        "type": '0' ,
        "loadUrl": link,
        "userdata": {}
      }
    }else if(linkType === 2){
      const { type , loadUrl , userdata} = JSON.parse(link);
      params = {
        "type": type ,
        "loadUrl": loadUrl,
        "userdata": userdata
      }
    }

    //ios 参数 
    const json = {
      "orgNum": "zxjt",
      "openNewPage":openNewPage,//0 悬浮当前直播页，1 跳转其他页面并悬浮当前页
      "direction": direction,
      "routeParam":JSON.stringify(params),//参考startAppPage
    }
    switch (channel) {
      case 'zxjt':
        if (window.terminal.isZxjtIos) {
          window.webkit.messageHandlers.openNewPageInLiveVideo.postMessage(json);
        } else {
          KDS_Native.openNewPageInLiveVideo("zxjt", direction, openNewPage, JSON.stringify(params));
        }
        break;
      default:
        break;
    }
  },
  linkUrlFloatVideo(item) {
    switch (channel) {
      case 'zxjt':
        if (window.terminal.isZxjtApp) {
              if (store.state.videoIsPlay && store.state.appVersionBoolean) {
                this.floatSendData(item);                                          
              } else {
                this.zxjtAppLink(item);
              }            
        } else {
          window.location.href = item.link;
        }
        break;
      case 'zxjtqh':
        this.zxjtqhLinkUrl(item.link)
        break;
      default:
        window.location.href = item.link;
        break;
    }
  },
  zxjtAppLink(item) {
    //linkType 1 url  2 json
    const {linkType,link}  = item;
    if(linkType === 1){
      if (window.terminal.isZxjtAndroid) {
        let userDataJson = JSON.stringify({});
        KDS_Native.startAppPage(0, link, userDataJson);
      } else if (window.terminal.isZxjtIos) {
        let linkData = JSON.stringify({ "type": 0, "loadUrl": link, "userdata": {} })
        window.webkit.messageHandlers.startAppPage.postMessage(linkData);
      }
    }else if(linkType === 2){    
      if (window.terminal.isZxjtAndroid) {
        const obj = JSON.parse(link)
        //参数一定是一个字符串
        KDS_Native.startAppPage(obj.type, obj.loadUrl,JSON.stringify(obj.userdata));
      } else if (window.terminal.isZxjtIos) {
        let linkData = JSON.stringify(JSON.parse(link)) 
        window.webkit.messageHandlers.startAppPage.postMessage(linkData);
      }
    }    
  },
  shoppingLink(item) { 
    this.linkUrlFloatVideo(item)
  },
  MsyhClientInfo() {//版本信息 不能用
    return new Promise(function (resolve, reject) {
      if (window.terminal.android) {
        try {
          resolve(JSON.parse(window.SysClientJs.clientInfomation()))
        } catch (e) {
          console.log(e)
          //TODO handle the exception
        }
      } else if (window.terminal.ios) {
        native4MobileBank.callForSysClient('clientInformation').then(function (res) {
          console.log(JSON.parse(res))
          resolve(JSON.parse(res))
        })
      }
    })
  },
  //多余字体....
  wordlimit(text, length) {
    //替换掉所有的 html标签，得到Html标签中的内容
    let content = text.replace(/<\/?.+?>/g, "");
    let content1 = content.replace(/ /g, ""); //得到后的内容
    if (content1.length > length) { //超过length显示省略号
      return content1.substring(0, length) + '...'
    } else {
      return content1
    }
  },
  getIsCollect(roomidVid, scType) {//是否收藏
    axios.post("/h5live/querySc?vid=" + roomidVid + '&scType=' + scType).then( //scType=收藏类型,默认是视频，1是视频，2-房间
      res => {
        let {
          code
        } = res.data
        if (code == "000000") {
          store.dispatch("setCollect", true);
        } else {
          store.dispatch("setCollect", false);
        }
      },
      err => { }
    );
  },
  setLiveCollectFun(roomId, num) {
    // 神策打点（收藏 1 取消收藏 0）
    const { title, anchor, roomStatus } = store.state.roomDetail;
    $sensorsTrack('liveBroadcast_liveRoomDetailsPageFunctionClick', {
      page_name: `直播${['预告', '详情'][roomStatus]}页`,
      user_nickname: store.state.userInfo.nickname,
      live_room_id: roomId,
      live_room_name: title,
      live_room_status: ['预告', '直播中'][roomStatus],
      live_room_creator: anchor,
      function_name: ['取消收藏', '收藏'][num],
    });
    axios.post("/h5live/scRoom?roomId=" + roomId + "&status=" + num).then(
      res => {
        if (res.data.code == "000000" && num == "1") { //收藏
          //this.vantIconLoveColor = 'vant-love-red';
          store.dispatch("setCollect", true);
        } else if (res.data.code == "000000" && num == "0") { //取消收藏
          //this.vantIconLoveColor = 'vant-love-gray';
          store.dispatch("setCollect", false);
        } else if (res.data.code == "100002" || res.data.code == "100003") {
          store.dispatch("setCollect", false);
        } else {
          //console.log("收藏接口错误")
        }
      },
      err => {
        //console.log(err);
      }
    );
  },
  LiveAttentionFun(isguanzhu,anchor) {
    if(isguanzhu){
      axios.post(`/h5live/mini/cancelFollowAnchor/${anchor}`);
      isguanzhu=false;
    }else{
      axios.post(`/h5live/mini/followAnchor/${anchor}`);
      isguanzhu=true;
    }
    return isguanzhu
  },
  // 圆形
  circleImg(ctx, img, x, y, r) {
    ctx.save();
    let d = r * 2;
    let cx = x + r;
    let cy = y + r;
    ctx.arc(cx, cy, r, 0, 2 * Math.PI);
    ctx.strokeStyle = 'rgba(255, 255, 255, 0)'; // 设置绘制圆形边框的
    ctx.stroke(); // 绘制出圆形，默认为黑色，可通过 ctx.strokeStyle = '#FFFFFF'， 设置想要的颜色
    ctx.clip();
    ctx.drawImage(img, x, y, d, d);
    ctx.restore();
  },
  //  画圆角矩形
  fillRoundRect(cxt, x, y, width, height, radius, fillColor) {
    //圆的直径必然要小于矩形的宽高
    if (2 * radius > width || 2 * radius > height) { return false; }
    cxt.save();
    cxt.translate(x, y);
    //绘制圆角矩形的各个边
    this.drawRoundRectPath(cxt, width, height, radius);
    cxt.fillStyle = fillColor || "rgba(22, 22, 22, 0.75)"; //若是给定了值就用给定的值否则给予默认值
    cxt.fill();
    cxt.restore();
  },
  drawRoundRectPath(cxt, width, height, radius) {
    cxt.beginPath(0);
    //从右下角顺时针绘制，弧度从0到1/2PI
    cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
    //矩形下边线
    cxt.lineTo(radius, height);
    //左下角圆弧，弧度从1/2PI到PI
    cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
    //矩形左边线
    cxt.lineTo(0, radius);
    //左上角圆弧，弧度从PI到3/2PI
    cxt.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);
    //上边线
    cxt.lineTo(width - radius, 0);
    //右上角圆弧
    cxt.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);
    //右边线
    cxt.lineTo(width, height - radius);
    cxt.closePath();
  },
  //压缩 base64
  dealImage(base64, w, callback) {
    var newImage = new Image();
    var quality = 0.7;    //压缩系数0-1之间
    newImage.src = base64;
    newImage.setAttribute("crossOrigin", 'Anonymous');	//url为外域时需要
    var imgWidth, imgHeight;
    newImage.onload = function () {
      imgWidth = this.width;
      imgHeight = this.height;
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      if (Math.max(imgWidth, imgHeight) > w) {
        if (imgWidth > imgHeight) {
          canvas.width = w;
          canvas.height = w * imgHeight / imgWidth;
        } else {
          canvas.height = w;
          canvas.width = w * imgWidth / imgHeight;
        }
      } else {
        canvas.width = imgWidth;
        canvas.height = imgHeight;
        quality = 0.6;
      }
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(this, 0, 0, canvas.width, canvas.height);
      var base64 = canvas.toDataURL("image/jpeg", quality); //压缩语句
      // 如想确保图片压缩到自己想要的尺寸,如要求在50-150kb之间，请加以下语句，quality初始值根据情况自定
      // while (base64.length / 1024 > 100) {
      // 	quality -= 0.01;
      // 	base64 = canvas.toDataURL("image/jpeg", quality);
      // }
      // // 防止最后一次压缩低于最低尺寸，只要quality递减合理，无需考虑
      // while (base64.length / 1024 < 60) {
      // 	quality += 0.001;
      // 	base64 = canvas.toDataURL("image/jpeg", quality);
      // }
      callback(base64);
    }
  },
  loadBridge(url, callback = null) {
    var script = document.createElement('script')
    // onload fires even when script fails loads with an error.
    if (callback) {
      script.onload = callback
    }
    // onerror fires for malformed URLs.
    script.onerror = onerror
    script.src = url
    document.head.appendChild(script)
  },
  //中信建投期货 手机号登录--------------------------------------------
  gotoLogin () {
    /*********防止连续多次弹出登录页面begin**********/
    // if (window.globalIsLogin) {
    //   return;
    // }
    // window.globalIsLogin = true;
    // setTimeout(function () {
    //   window.globalIsLogin = null;
    // }, 2000);
    /*********防止连续多次弹出登录页面begin**********/
    //先查询有没有加密串
    this.getZxjtqhCacheData()

  },
  setZxjtqhCacheData(courseId){
    const paramMap = {
      "funcNo":"50042",
      "key":"courseId",
      "value":courseId
    }
    window.callMessageNative(paramMap);
  },
  getZxjtqhCacheData(){//获取中信建投期货缓存数据
    const paramMap = {
      "funcNo":"50043",
      "key":"login_userinfo_dzh"
    }
  let cacheData = window.callMessageNative(paramMap);
  console.log('获取加密参数',cacheData);
  if(window.terminal.ios){
    if(cacheData.results[0].value){//有加密参数
       //加密参数   cacheData.results[0].value  slice  去除前缀&params=
        this.appUserJoin(cacheData.results[0].value.slice(8),channel,Vue.prototype.$source)
    }else{//没有有加密参数
        this.zxjtqhLogin()           
    }
  }else if(window.terminal.android){
    if(Object.keys(cacheData.results[0]).length == 0){//没有加密参数
      this.zxjtqhLogin()
    }else{//有加密参数
      //加密参数   cacheData.results[0].value  slice  去除前缀&params=
      this.appUserJoin(cacheData.results[0].value.slice(8),channel,Vue.prototype.$source)
    }
  }

   
  },
  closeZxjtqhWebview(){
    const paramMap = {
      "moduleName": window.localStorage.getItem('urlModuleName') || 'liveHome',
      "funcNo" :"50114",
    };
    window.callMessageNative(paramMap)
  },
  zxjtqhLogin(){//登录
    console.log('调用app登录');
    const paramMap = {
      "moduleName": window.localStorage.getItem('urlModuleName') || 'liveHome',
      "funcNo" :"60041",
    };
    window.callMessageNative(paramMap)
  },
  //中信建投期货 分享--------------------------------------------
  zxjtqhShare (moduleName, shareTypeList, title, link, content, imgUrl) {
    const {shareTitle,shareDesc,shareIcon} = store.state.orgShareObj || {};//机构分享
		const {name,icon} = store.state.SysOrgInfo || {};
    let param = {};
    param["funcNo"] = "50230";//功能号
    param["moduleName"] = window.localStorage.getItem('urlModuleName') || 'liveHome';//模块名称 H5的模块名称，Android必传 (直播首页:liveHome 直播间:liveRoom)
    param["shareTypeList"] = shareTypeList;//分享平台的类型，多个用，分割（数据字典）值参照数据字典shareType
    param["title"] = title || shareTitle || `【${name}】一起来看直播吧！`;//分享标题
    param["link"] = link;//链接
    param["content"] = content||shareDesc||`精彩直播，尽在${name}手机直播！`;//内容
    param["imgUrl"] = imgUrl || shareIcon || icon ;//图片
    window.callMessageNative(param,(data)=>{
      console.log(data,'调用分享回调');
    })
  },
  zxjtqhLinkUrl(url,diffType){
    if(window.terminal.isZxjtqhApp){
        const title =  diffType == 'SC'? '':'中信建投期货'
        const paramMap = {
          "moduleName": "live",
          "funcNo" :"50115",
          url,
          "title":title,
          "titleColor":"#000000",
          "isShowBackBtn":"1"
        };
        window.callMessageNative(paramMap)
    }else{
      window.location.href = url;
    }   
  },
  //设置手机状态栏高度 --------------------------------------------
  setBarHeight (el, height, isMsg) {//el 容器元素 height状态栏高度
    if (isMsg) {//留言区高度
      setTimeout(() => {
        el.style.height = document.documentElement.clientHeight - height + 'px'
        el.style.paddingBottom = 24 + 'px'
      },300)

    } else {
      el.style.position = 'absolute'
      el.style.top = height + 'px'
      setTimeout(() => {
        el.style.height = document.documentElement.clientHeight - height + 'px'
      },300)
    }
  },
  initSourcePlat() {
    const ua = navigator.userAgent.toLowerCase();
    return new Promise(resolve => {
      if (ua.match(/microMessenger/i) == "micromessenger") {
          wx.miniProgram.getEnv(function(res) {
            if (res.miniprogram) {
              resolve("mini");
            } else {
              resolve("wx");
            }
          });
          if(ua.match(/wxwork/i) == 'wxwork'){
            resolve("wxwork");
          }
      } else if(window.terminal.android|| window.terminal.ios){
        resolve("app");
      }else{
        resolve("web");
      }
    });
  },

  // 跳转
  handleEnterCourse(course) {
    const { totalLessonNum, courseId } = course;
    console.log('course:',course);
    // 无课程ID拦截
    if (!courseId) {
      this.toastMessage('未找到课程信息');
      return false;
    }
    if (totalLessonNum && totalLessonNum > 1) { /* totalLessonNum && totalLessonNum > 1 */
      // 课程详情
      Vue.prototype.$myrouter.push(`/${window.channel}/courseDetail?courseId=${courseId}`);
    } else {
      // 课节（查询课程的第一个课节的关联vid）
      axios.get("/h5live/course/getCourseInfo", {
        params: {
          courseId,
        }
      }).then(res => {
        if(res.data.code === "000000") {
          // 跳转回看
          const { vid } = res.data.data.lessons[0];
          Vue.prototype.$myrouter.push(`/${window.channel}/liveBack/${vid}?dzhPage=true`);
        } else {
          return Promise.reject(res.data);
        }
      }).catch(err => {
        console.error(err);
      });
    }
  },
  // 购买课程
  handleBuyCourse(course) {
    const { haveBuy, priceType, courseId } = course;
    // 判断是否购买
    if (haveBuy) {
      console.log('进入课程');
      this.handleEnterCourse(course);
    } else {
      if (priceType === 0) {
        // 免费
        console.log('订阅');
        axios.post("/h5live/course/subscribeCourse", {}, {
          params: {
            courseId
          },
        }).then(res => {
          if(res.data.code === "000000") {
            this.toastMessage('订阅成功，正在跳转...');
            // setTimeout(() => {
            //   location.reload();
            // }, 500);
          } else {
            return Promise.reject(res.data);
          }
        }).catch(err => {
          console.error(err);
        });
      } else {
        // 付费
        console.log('跳转购买页');
        if (this.getPlatform() === 'app') {
          // 打开商城页
          this.setZxjtqhCacheData(courseId)
          this.zxjtqhLinkUrl(`${config.zxjtqhShoppingUrl}?returnUrl=${location.href}&courseId=${courseId}&topmargin=${window.topmargin}`,'SC');
        } else {
          // 拉起app/app下载
          window.open('https://app.cfc108.com:7443/download.html');
        }
      }
    }
  },
  initAxiosPlatform() {
    //1 app 2 wx 3 mini
    const ua = navigator.userAgent.toLowerCase();
    return new Promise(resolve => {
      if (ua.match(/microMessenger/i) == "micromessenger") {
          wx.miniProgram.getEnv(function(res) {
            if (res.miniprogram) {
              resolve("mini");
            } else {
              resolve("wx");
            }
          });
      } else if(window.terminal.android|| window.terminal.ios){
        resolve("app");
      }else{
        resolve("app");
      }
    });
  },
  isMobile() {
    let userAgentInfo = navigator.userAgent;
    console.log('userAgentInfo:',userAgentInfo);
    let Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod'];
    let getArr = Agents.filter(i => userAgentInfo.includes(i));
    if(getArr.length){
      store.commit("setIsMobile", true)
      return true
    }else{
      return false
    }
  },
  //字符串参数替换
  replaceQueryString (url, name, value) {
    const re = new RegExp(name + '=[^&]*', 'gi')
    return url.replace(re, name + '=' + value)
  },
  //曝光率方法
  obServerDom(selectDom){
      //异步 this.$nextTick()
      const  ob = new IntersectionObserver((entries)=>{
        entries.forEach((i) => {
          if (i.isIntersecting) {//进入视口
            console.log(i.target);
            //你要实现的代码逻辑
          }
          //ob.unobserve(target)//取消观察
        });
      },{
        //配置项
        root:null,
        threshold: 1.0,
        rootMargin:0,
      })
      const queryDom = document.querySelectorAll(selectDom);
      queryDom.length &&  queryDom.forEach((item)=>{
        ob.observe(item)
      })
  },
      /*
     *  画图片圆角 封面图
     *  ctx Canvas实例
     *  img 图片地址
     *   x  x轴坐标
     *   y  y轴坐标
     *   w  宽度
     *   h  高度
     *   r  弧度大小
     */
      drawRoundRect(ctx, r, x, y, w, h, img) {
        ctx.save();
        if (w < 2 * r) r = w / 2;
        if (h < 2 * r) r = h / 2;
        ctx.beginPath();
        ctx.moveTo(x + r, y);
        ctx.arcTo(x + w, y, x + w, y + h, r);
        ctx.arcTo(x + w, y + h, x, y + h, r);
        ctx.arcTo(x, y + h, x, y, r);
        ctx.arcTo(x, y, x + w, y, r);
        ctx.closePath();
        ctx.clip();
        ctx.drawImage(img, x, y, w, h);
        ctx.restore(); // 返回上一状态
      },
         /*
     *  画图片圆角 右上 左上
     *  ctx Canvas实例
     *  img 图片地址
     *   x  x轴坐标
     *   y  y轴坐标
     *   w  宽度
     *   h  高度
     *   r  弧度大小
     */
    drawRoundRectTopRightLeft(ctx, r, x, y, w, h, img) {
      ctx.save();
      if (w < 2 * r) r = w / 2;
      if (h < 2 * r) r = h / 2;
      ctx.beginPath();
      ctx.moveTo(x + r, y);
      ctx.arcTo(x + w, y, x + w, y + h, r);
      ctx.arcTo(x + w, y + h, x, y + h, 0);
      ctx.arcTo(x, y + h, x, y, 0);
      ctx.arcTo(x, y, x + w, y, r);
      ctx.closePath();
      ctx.clip();
      ctx.drawImage(img, x, y, w, h);
      ctx.restore(); // 返回上一状态
    },
    liveBackFun(){
      const curUrl = window.location.href;
      if(window.terminal.weixin){//微信				
				if(curUrl.includes('dzhPage')){//自己页面跳转
					window.history.go(-1);
				}else{
					wx.closeWindow();
				}                
			}else{
        if(curUrl.includes('dzhPage')){
            window.history.go(-1)
        }else{
          if(window.terminal.isZxjtqhApp){
              this.closeZxjtqhWebview()
          }else if(window.terminal.isZxjtApp){//关闭webview
              if (window.terminal.isZxjtIos) {
                window.webkit.messageHandlers.closeCurrentWindow.postMessage("");
              } else if(window.terminal.isZxjtAndroid){
                KDS_Native.closeCurrentWindow();
              }
          }else{
            window.history.go(-1)
          }  
        }               
			}
    },
//字体换行，可以限制换行条数
			/**
			ctx： 画布的上下文环境
			content： 需要绘制的文本内容
			drawX： 绘制文本的x坐标
			drawY： 绘制文本的y坐标
			lineHeight：文本之间的行高
			lineMaxWidth：每行文本的最大宽度
			lineNum：最多绘制的行数
			*/
			textPrewrap(ctx, content, drawX, drawY, lineHeight, lineMaxWidth, lineNum) {
				var drawTxt = ''; // 当前绘制的内容
				var drawLine = 1; // 第几行开始绘制
				var drawIndex = 0; // 当前绘制内容的索引
				// 判断内容是否可以一行绘制完毕
				if (ctx.measureText(content).width <= lineMaxWidth) {
					ctx.fillText(content.substring(drawIndex, i), drawX, drawY);
				} else {
						for (var i = 0; i < content.length; i++) {
						drawTxt += content[i];
						if (ctx.measureText(drawTxt).width >= lineMaxWidth) {
							if (drawLine >= lineNum) {
								ctx.fillText(content.substring(drawIndex, i) + '...', drawX, drawY);
								
								break;
							} else {
								ctx.fillText(content.substring(drawIndex, i + 1), drawX, drawY);
								drawIndex = i + 1;
								drawLine += 1;
								drawY += lineHeight;
								drawTxt = '';
							}
						} else {
							// 内容绘制完毕，但是剩下的内容宽度不到lineMaxWidth
							if (i === content.length - 1) {
								ctx.fillText(content.substring(drawIndex), drawX, drawY);
								
							}
						}
					}
				}
			},
      shareDotNumFun(roomBackInfo){
        const {fromTypeLiveBack} = roomBackInfo;
        if(fromTypeLiveBack === 'live'){
           const {anchor,roomStatus,sid,roomId} = roomBackInfo;
           const params = {
            anchor,
            'roomId':roomId,
            'streamType': roomStatus == 0 ? '1' :'2',
            'sceneId':sid,
          }
           shareDotNum(params)
        }else if(fromTypeLiveBack === 'back'){
           const {vid,roomId,creator} = roomBackInfo;
           const params = {
            'anchor':creator,
            roomId,
            'streamType': '3',
            'sceneId':vid,
          }
           shareDotNum(params)
        }
      },
      //中信建投app 登录回调
      appZxjtLoginInfoCallBack(source){
          return new Promise((resolve,reject) =>{
              window.setUserInfo = (data)=>{
                console.log("app setUserInfo",data);
                let  verStr = data.appVersion;
                if(window.terminal.ios){
                  verStr = verStr.substring(4)
                }       
                const ver = window.versionCompare(verStr,'8.2.2');
                if(ver > -1){
                  const curUrl = window.location.href;
                  if(curUrl.includes('liveBack') || curUrl.includes('liveRoom')){
                      const sessMode = window.sessionStorage.getItem('mode');
                      if( sessMode == 0){//横屏
                        store.commit('setShowMarginTop',true);//设置头部
                      }else{
                        store.commit('setShowMarginTop',false);
                      }
                  }else{
                    store.commit('setShowMarginTop',true);
                  }
                  store.commit("setAppVersion", true);//app版本
                 
                }else{
                  store.commit("setAppVersion", false);
                  store.commit('setShowMarginTop',false);
                } 
                if(data?.phone){                   
                    if(data?.custInfo?.custId){
                      //资金账号登录
                      console.log('resolve-riskPrivate');
                      resolve('riskPrivate')
                    }else{
                       // 手机号登录
                      console.log('resolve-phoneLogin');
                      resolve('phoneLogin');
                    }
                }else{
                  //未登录
                  console.log('resolve-logOut');
                  resolve('logOut');
                }      
                if(data && data.userId && data.userId.length > 0){
                  store.commit('setZjzhInfo', data) // 全局同步用户信息
                  console.log("userId is ", data.userId)
                  let userId = data.userId
                  let phone =  data.phone
                  let avatar = data.avatar != undefined ? data.avatar : ''
                  let nickName = data.nickName != undefined ? data.nickName : ''
                  this.appUserJoin(aes.encrypt(JSON.stringify({userId,phone,avatar,nickName})), channel, 'app').then(res => {}, err => {
                    if (err == 'yk') {
                      this.buildYk(channel).then(resToken => {
                        store.dispatch("setYk", true)
                        this.initVue(resToken, channel, source)
                      }, err => {
                        this.gotoBusyPage()
                      })
                    }
                  })
                }else{
                  this.buildYk(channel).then(resToken => {
                    store.dispatch("setYk", true)
                    this.initVue(resToken, channel, source)
                  }, err => {
                    this.gotoBusyPage()
                  })
                }
              }
          })
      },
}
